"""
Content Management API Router
内容管理API路由
"""

import uuid
from typing import Optional, List, Dict, Any
from datetime import datetime

from fastapi import APIRouter, Depends, HTTPException, status, Query, File, UploadFile
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, and_, or_, desc

from ..core.database import get_db
from ..core.logging import error_logger
from ..core.exceptions import (
    ContentNotFoundError,
    ContentValidationError,
    PermissionDeniedError,
    ValidationError,
    FileNotFoundError,
)
from ..models.user import User
from ..models.generated_content import GeneratedContent, ContentStatus
from ..models.creation_request import CreationRequest
from ..models.folder import Folder
from ..services.content_management_service import ContentManagementService
from ..services.content_generation_service import ContentGenerationService
from ..services.file_storage_service import FileStorageService
from .auth import get_current_user

router = APIRouter()


@router.post("/create", response_model=dict, summary="创建内容", description="""
创建AI生成内容，支持多种内容类型和AI提供商。

### 功能说明
- 支持文本生成图片、视频、音频、文本内容
- 集成多个AI提供商（豆包、阿里云、OpenAI）
- 智能参数验证和内容过滤
- 异步任务队列处理，支持批量生成
- 自动生成内容标签和元数据

### 内容类型支持
- **image**: 文本生成图片，支持多种分辨率和风格
- **video**: 文本生成视频，支持时长和分辨率设置  
- **audio**: 文本生成音频，支持语音选择和语速调节
- **text**: 文本生成文本，支持多种写作风格

### AI提供商
- **doubao**: 豆包大模型（推荐，中文优化）
- **ali**: 阿里云大模型
- **openai**: OpenAI GPT/DALL-E

### 请求参数
- **prompt**: 生成提示词，描述想要生成的内容
- **content_type**: 内容类型，必需参数
- **ai_provider**: AI提供商，默认为豆包
- **folder_id**: 目标文件夹ID，可选
- **parameters**: 额外参数字典，包含模型特定参数
- **negative_prompt**: 负面提示词，排除不需要的元素
- **width/height**: 图片尺寸，仅图片类型有效
- **quality**: 质量等级，影响生成时间和效果
- **style**: 风格参数，如写实、卡通、抽象等
- **count**: 生成数量，支持批量生成（1-10）

### 响应数据
```json
{
    "success": true,
    "message": "内容创建请求已提交",
    "request_id": "req_123456",
    "task_id": "task_789012",
    "estimated_completion_time": "2024-01-15T15:30:00",
    "content_preview": {
        "prompt": "美丽的日落风景",
        "content_type": "image",
        "provider": "doubao",
        "parameters": {"size": "1024x1024", "quality": "high"}
    }
}
```

### 错误码
- **400**: 参数验证失败（如内容类型不支持、参数超出范围）
- **401**: 未认证或令牌无效
- **403**: 用户权限不足或超出每日生成限制
- **422**: 请求格式错误
- **500**: 服务器内部错误
- **503**: AI服务不可用

### 使用示例
```bash
# 生成图片
curl -X POST "http://localhost:8000/api/v1/content/create" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "美丽的日落风景，油画风格",
    "content_type": "image",
    "ai_provider": "doubao",
    "width": 1024,
    "height": 1024,
    "quality": "high",
    "style": "oil_painting"
  }'

# 批量生成
curl -X POST "http://localhost:8000/api/v1/content/create" \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "现代简约logo设计",
    "content_type": "image",
    "count": 5,
    "quality": "standard"
  }'
```
""")
async def create_content(
    prompt: str,
    content_type: str = Query(..., description="内容类型: image, video, audio, text"),
    ai_provider: str = Query("doubao", description="AI提供商: doubao, ali, openai"),
    folder_id: Optional[str] = Query(None, description="目标文件夹ID"),
    parameters: Optional[Dict[str, Any]] = None,
    negative_prompt: Optional[str] = None,
    width: Optional[int] = Query(None, ge=64, le=4096),
    height: Optional[int] = Query(None, ge=64, le=4096),
    quality: Optional[str] = Query("high", description="质量等级: low, medium, high, ultra"),
    style: Optional[str] = None,
    count: Optional[int] = Query(1, ge=1, le=10, description="生成数量"),
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """创建内容 - 文生图/文生视频/文生音频"""
    try:
        content_service = ContentManagementService(db)
        generation_service = ContentGenerationService(db)
        
        # 验证用户权限和限制
        if not current_user.can_generate_content():
            raise HTTPException(
                status_code=status.HTTP_403_FORBIDDEN,
                detail="用户权限不足或存储空间已满"
            )
        
        # 创建内容生成请求
        creation_request = await generation_service.create_content_request(
            user=current_user,
            prompt=prompt,
            content_type=content_type,
            ai_provider=ai_provider,
            parameters={
                "negative_prompt": negative_prompt,
                "width": width,
                "height": height,
                "quality": quality,
                "style": style,
                "count": count,
                **(parameters or {})
            }
        )
        
        # 如果指定了文件夹，验证文件夹存在且属于用户
        target_folder = None
        if folder_id:
            folder_result = await db.execute(
                select(Folder).where(
                    and_(
                        Folder.id == uuid.UUID(folder_id),
                        Folder.user_id == current_user.id
                    )
                )
            )
            target_folder = folder_result.scalar_one_or_none()
            if not target_folder:
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail="文件夹不存在或无权限访问"
                )
        
        # 提交生成任务到队列
        from ..core.task_queue import task_queue
        from ..services.ai_model_service import AIModelService
        
        ai_service = AIModelService()
        
        task_ids = []
        for i in range(count):
            task_id = await task_queue.submit_task(
                generation_service.generate_content_async,
                args=(creation_request.id, ai_service, i + 1),
                priority=5,
                max_retries=3,
                user_id=current_user.id
            )
            task_ids.append(task_id)
        
        return {
            "success": True,
            "data": {
                "request_id": str(creation_request.id),
                "task_ids": [str(task_id) for task_id in task_ids],
                "status": creation_request.status,
                "estimated_time": creation_request.estimated_completion_time,
                "folder_id": folder_id,
            },
            "message": f"内容生成任务已提交，预计{creation_request.estimated_completion_time}秒完成"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        error_logger.log_error(
            e, {
                "operation": "content_creation", 
                "user_id": str(current_user.id),
                "prompt": prompt,
                "content_type": content_type
            }
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="内容创建失败，请稍后重试"
        )


@router.get("/{content_id}")
async def get_content(
    content_id: str,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """获取内容详情"""
    try:
        content_service = ContentManagementService(db)
        
        # 获取内容
        content = await content_service.get_content(
            uuid.UUID(content_id), 
            current_user
        )
        
        if not content:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="内容不存在或无权限访问"
            )
        
        # 增加查看次数
        content.increment_view_count()
        await db.commit()
        
        return {
            "success": True,
            "data": {
                "id": str(content.id),
                "title": content.title,
                "description": content.description,
                "content_type": content.content_type,
                "format": content.format,
                "status": content.status,
                "file_info": content.get_file_info(),
                "generation_info": content.get_generation_info(),
                "quality_info": content.get_quality_info(),
                "folder_id": str(content.folder_id) if content.folder_id else None,
                "is_public": content.is_public,
                "is_favorite": content.is_favorite,
                "view_count": content.view_count,
                "download_count": content.download_count,
                "tags": content.tags or [],
                "content_metadata": content.content_metadata or {},
                "created_at": content.created_at.isoformat(),
                "generated_at": content.generated_at.isoformat() if content.generated_at else None,
                "processing_time": content.processing_time_seconds,
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        error_logger.log_error(
            e, {
                "operation": "get_content",
                "content_id": content_id,
                "user_id": str(current_user.id)
            }
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取内容失败，请稍后重试"
        )


@router.get("/", response_model=dict, summary="获取内容列表", description="""
获取当前用户的内容列表，支持多种筛选和排序方式。

### 功能说明
- 分页获取用户的内容列表
- 支持多种筛选条件（类型、状态、文件夹、收藏等）
- 支持关键词搜索
- 支持多种排序方式
- 返回内容预览信息和统计

### 筛选参数
- **content_type**: 按内容类型筛选（image, video, audio, text）
- **status**: 按内容状态筛选（pending, processing, completed, failed）
- **folder_id**: 按文件夹筛选，返回指定文件夹内的内容
- **is_favorite**: 按收藏状态筛选
- **search**: 关键词搜索，搜索标题、描述、标签等字段

### 分页参数
- **page**: 页码，从1开始
- **page_size**: 每页数量，最大100

### 排序参数
- **sort_by**: 排序字段（created_at, updated_at, file_size, title）
- **sort_order**: 排序方向（asc升序，desc降序）

### 响应数据
```json
{
    "success": true,
    "data": {
        "items": [
            {
                "id": "content_123",
                "title": "美丽的日落风景",
                "content_type": "image",
                "status": "completed",
                "file_url": "http://localhost:8000/content/image.png",
                "file_size": 2048576,
                "mime_type": "image/png",
                "width": 1024,
                "height": 1024,
                "created_at": "2024-01-15T12:00:00",
                "folder": {"id": "folder_456", "name": "风景图片"},
                "tags": ["风景", "日落", "自然"],
                "is_favorite": true,
                "ai_provider": "doubao",
                "generation_params": {"quality": "high", "style": "realistic"}
            }
        ],
        "total": 150,
        "page": 1,
        "page_size": 20,
        "total_pages": 8,
        "has_next": true,
        "has_prev": false
    },
    "summary": {
        "total_content": 150,
        "by_type": {"image": 100, "video": 30, "audio": 15, "text": 5},
        "by_status": {"completed": 140, "processing": 5, "failed": 5},
        "total_storage_mb": 2048
    }
}
```

### 错误码
- **401**: 未认证或令牌无效
- **422**: 参数验证失败
- **500**: 服务器内部错误

### 使用示例
```bash
# 获取所有内容
curl -X GET "http://localhost:8000/api/v1/content/" \
  -H "Authorization: Bearer YOUR_TOKEN"

# 筛选图片内容，按创建时间排序
curl -X GET "http://localhost:8000/api/v1/content/?content_type=image&sort_by=created_at&sort_order=desc" \
  -H "Authorization: Bearer YOUR_TOKEN"

# 搜索关键词，分页获取
curl -X GET "http://localhost:8000/api/v1/content/?search=风景&page=1&page_size=50" \
  -H "Authorization: Bearer YOUR_TOKEN"

# 获取指定文件夹的内容
curl -X GET "http://localhost:8000/api/v1/content/?folder_id=folder_123" \
  -H "Authorization: Bearer YOUR_TOKEN"
```
""")
async def list_content(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    content_type: Optional[str] = Query(None, description="内容类型筛选"),
    status: Optional[str] = Query(None, description="状态筛选"),
    folder_id: Optional[str] = Query(None, description="文件夹筛选"),
    is_favorite: Optional[bool] = Query(None, description="收藏筛选"),
    search: Optional[str] = Query(None, description="搜索关键词"),
    sort_by: Optional[str] = Query("created_at", description="排序字段"),
    sort_order: Optional[str] = Query("desc", description="排序方向: asc, desc"),
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """获取内容列表"""
    try:
        content_service = ContentManagementService(db)
        
        # 构建查询条件
        filters = {"user_id": current_user.id}
        
        if content_type:
            filters["content_type"] = content_type
        if status:
            filters["status"] = status
        if folder_id:
            filters["folder_id"] = uuid.UUID(folder_id)
        if is_favorite is not None:
            filters["is_favorite"] = is_favorite
        if search:
            filters["search"] = search
        
        # 获取内容列表
        result = await content_service.list_content(
            page=page,
            page_size=page_size,
            filters=filters,
            sort_by=sort_by,
            sort_order=sort_order
        )
        
        # 格式化返回数据
        items = []
        for content in result["items"]:
            items.append({
                "id": str(content.id),
                "title": content.title,
                "content_type": content.content_type,
                "format": content.format,
                "status": content.status,
                "thumbnail_url": content.thumbnail_url,
                "file_size_readable": content.file_size_readable,
                "width": content.width,
                "height": content.height,
                "is_favorite": content.is_favorite,
                "view_count": content.view_count,
                "download_count": content.download_count,
                "folder_id": str(content.folder_id) if content.folder_id else None,
                "created_at": content.created_at.isoformat(),
                "generated_at": content.generated_at.isoformat() if content.generated_at else None,
            })
        
        return {
            "success": True,
            "data": {
                "items": items,
                "total": result["total"],
                "page": page,
                "page_size": page_size,
                "total_pages": result["total_pages"],
                "has_next": result["has_next"],
                "has_prev": result["has_prev"],
            }
        }
        
    except Exception as e:
        error_logger.log_error(
            e, {
                "operation": "list_content",
                "user_id": str(current_user.id),
                "filters": locals().get("filters", {})
            }
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取内容列表失败，请稍后重试"
        )


@router.put("/{content_id}")
async def update_content(
    content_id: str,
    title: Optional[str] = None,
    description: Optional[str] = None,
    folder_id: Optional[str] = None,
    is_favorite: Optional[bool] = None,
    is_public: Optional[bool] = None,
    tags: Optional[List[str]] = None,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """更新内容信息"""
    try:
        content_service = ContentManagementService(db)
        
        # 准备更新数据
        update_data = {}
        if title is not None:
            update_data["title"] = title
        if description is not None:
            update_data["description"] = description
        if is_favorite is not None:
            update_data["is_favorite"] = is_favorite
        if is_public is not None:
            update_data["is_public"] = is_public
        if tags is not None:
            update_data["tags"] = tags
        
        # 如果更新文件夹，验证文件夹存在且属于用户
        if folder_id is not None:
            if folder_id == "":  # 空字符串表示移除文件夹
                update_data["folder_id"] = None
            else:
                folder_result = await db.execute(
                    select(Folder).where(
                        and_(
                            Folder.id == uuid.UUID(folder_id),
                            Folder.user_id == current_user.id
                        )
                    )
                )
                if not folder_result.scalar_one_or_none():
                    raise HTTPException(
                        status_code=status.HTTP_404_NOT_FOUND,
                        detail="文件夹不存在或无权限访问"
                    )
                update_data["folder_id"] = uuid.UUID(folder_id)
        
        # 更新内容
        success = await content_service.update_content(
            uuid.UUID(content_id),
            current_user,
            update_data
        )
        
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="内容不存在或无权限更新"
            )
        
        return {
            "success": True,
            "message": "内容更新成功"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        error_logger.log_error(
            e, {
                "operation": "update_content",
                "content_id": content_id,
                "user_id": str(current_user.id),
                "update_data": update_data
            }
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="内容更新失败，请稍后重试"
        )


@router.delete("/{content_id}")
async def delete_content(
    content_id: str,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """删除内容"""
    try:
        content_service = ContentManagementService(db)
        file_service = FileStorageService()
        
        # 删除内容（包含文件）
        success = await content_service.delete_content(
            uuid.UUID(content_id),
            current_user,
            file_service
        )
        
        if not success:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="内容不存在或无权限删除"
            )
        
        return {
            "success": True,
            "message": "内容删除成功"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        error_logger.log_error(
            e, {
                "operation": "delete_content",
                "content_id": content_id,
                "user_id": str(current_user.id)
            }
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="内容删除失败，请稍后重试"
        )


@router.post("/{content_id}/download")
async def download_content(
    content_id: str,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """下载内容"""
    try:
        content_service = ContentManagementService(db)
        file_service = FileStorageService()
        
        # 获取内容
        content = await content_service.get_content(
            uuid.UUID(content_id), 
            current_user
        )
        
        if not content:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="内容不存在或无权限访问"
            )
        
        if content.status != "completed":
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="内容尚未生成完成"
            )
        
        # 生成下载链接
        download_url = await file_service.generate_download_url(
            content.file_path,
            content.file_name,
            expires_in=3600  # 1小时有效期
        )
        
        # 增加下载次数
        content.increment_download_count()
        await db.commit()
        
        return {
            "success": True,
            "data": {
                "download_url": download_url,
                "file_name": content.file_name,
                "file_size": content.file_size_bytes,
                "expires_at": datetime.utcnow().timestamp() + 3600
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        error_logger.log_error(
            e, {
                "operation": "download_content",
                "content_id": content_id,
                "user_id": str(current_user.id)
            }
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="生成下载链接失败，请稍后重试"
        )


@router.post("/{content_id}/favorite")
async def toggle_favorite(
    content_id: str,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """切换收藏状态"""
    try:
        content_service = ContentManagementService(db)
        
        # 获取内容
        content = await content_service.get_content(
            uuid.UUID(content_id), 
            current_user
        )
        
        if not content:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="内容不存在或无权限访问"
            )
        
        # 切换收藏状态
        content.is_favorite = not content.is_favorite
        await db.commit()
        
        return {
            "success": True,
            "data": {
                "is_favorite": content.is_favorite
            },
            "message": "已收藏" if content.is_favorite else "已取消收藏"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        error_logger.log_error(
            e, {
                "operation": "toggle_favorite",
                "content_id": content_id,
                "user_id": str(current_user.id)
            }
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="操作失败，请稍后重试"
        )


@router.get("/{content_id}/status")
async def get_content_status(
    content_id: str,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db),
):
    """获取内容状态"""
    try:
        content_service = ContentManagementService(db)
        
        # 获取内容
        content = await content_service.get_content(
            uuid.UUID(content_id), 
            current_user
        )
        
        if not content:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="内容不存在或无权限访问"
            )
        
        # 获取相关任务状态
        from ..models.task_queue import TaskQueue
        task_result = await db.execute(
            select(TaskQueue).where(
                and_(
                    TaskQueue.related_content_id == content.id,
                    TaskQueue.status.in_(["pending", "processing"])
                )
            ).order_by(desc(TaskQueue.created_at))
        )
        active_tasks = task_result.scalars().all()
        
        return {
            "success": True,
            "data": {
                "id": str(content.id),
                "status": content.status,
                "progress": getattr(content, 'progress', 0),
                "processing_time": content.processing_time_seconds,
                "error_message": content.error_message,
                "error_code": content.error_code,
                "created_at": content.created_at.isoformat(),
                "generated_at": content.generated_at.isoformat() if content.generated_at else None,
                "active_tasks": [
                    {
                        "task_id": str(task.id),
                        "status": task.status.value if hasattr(task.status, 'value') else str(task.status),
                        "progress": task.progress,
                        "created_at": task.created_at.isoformat(),
                    }
                    for task in active_tasks
                ]
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        error_logger.log_error(
            e, {
                "operation": "get_content_status",
                "content_id": content_id,
                "user_id": str(current_user.id)
            }
        )
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="获取状态失败，请稍后重试"
        )


# 导出路由
__all__ = ["router"]